package com.hollycrm.unicom.code.web;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.commons.beanutils.PropertyUtils;

import com.hollycrm.springframework.factory.DefaultBeanFactory;
import com.hollycrm.unicom.code.CodeManager;
import com.hollycrm.unicom.usersupport.DepartmentTreeViewObject;

/**
 * DepartmentLabelTag
*
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: </p>
 * @author Tian Kai
 * @version 1.0
 */
public class DepartmentLabelTag extends BodyTagSupport {

    private Object nameBean;
    private String name;
    private String deptKey;
    private String deptKeyProperty;

    public int doStartTag() throws JspException {

        DepartmentTreeViewObject department = null;
        CodeManager codeManager = (CodeManager) DefaultBeanFactory.getBean(CodeManager.BEAN_ID);

        if (deptKey != null) {
            department = codeManager.getDepartment(deptKey);
        }
        else {
            nameBean = pageContext.findAttribute(name);
            if (nameBean == null) throw new JspException("not find bean: " + name + " in any scope.");
            try {
                if (nameBean instanceof String)
                    department = codeManager.getDepartment((String) nameBean);
                else
                    department = codeManager.getDepartment( (String)
                        PropertyUtils.getProperty(nameBean, deptKeyProperty));
            }
            catch (Exception ex) {
                throw new JspException("tag problemKeyProperty: " +
                                       deptKeyProperty + ex.getMessage());
            }
        }

        if (department != null) {
            try {
                pageContext.getOut().print(department.getName() == null ?
                                             "" : department.getName());
            }
            catch (IOException ex1) {
                throw new JspException(ex1);
            }
        }

        return (SKIP_BODY);
    }

    public void release() {
        super.release();
        nameBean = null;
        name = null;
        deptKey = null;
        deptKeyProperty = null;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDeptKey() {
        return deptKey;
    }
    public void setDeptKey(String deptKey) {
        this.deptKey = deptKey;
    }
    public String getDeptKeyProperty() {
        return deptKeyProperty;
    }
    public void setDeptKeyProperty(String deptKeyProperty) {
        this.deptKeyProperty = deptKeyProperty;
    }

}
